/*
 * form_filling.cpp
 *
 *  Created on: 11/12/2008
 *      Author: desadoc
 */

#include "form_filling.h"

/****************************************************************************

Tallulah - Projeto LES

****************************************************************************/

#include <QtGui>
#include <QTableWidgetItem>

#include "mdichild.h"

form_filling::form_filling()
{
	qt = 0;
	layout = new QVBoxLayout;
	formLay = new QVBoxLayout;
	formLay->setDirection(QBoxLayout::Down);

	botoes = new QWidget;
	botLay = new QHBoxLayout;
	add = new QPushButton;
	del = new QPushButton;
	next = new QPushButton;
	previous = new QPushButton;

	del->setEnabled(false);
	next->setEnabled(false);
	previous->setEnabled(false);

	curNum = new QSpinBox;
	curNum->setDisabled(true);
	curNum->setValue(0);

	add->setText(tr("Adicionar"));
	del->setText(tr("Remover"));
	next->setText(tr("Proximo"));
	previous->setText(tr("Anterior"));
	botLay->addWidget(add);
	botLay->addWidget(del);
	botLay->addWidget(next);

	botLay->addWidget(curNum);

	botLay->addWidget(previous);

	botoes->setLayout(botLay);

	scrollArea = new QScrollArea(this);
	scrollArea->setObjectName(QString::fromUtf8("scrollArea"));
	scrollArea->setEnabled(true);
	scrollArea->setGeometry(QRect(0, 0, 781, 331));
	scrollArea->setMinimumSize(QSize(781, 331));
	scrollArea->setLineWidth(0);
	scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
	scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
	scrollArea->setWidgetResizable(true);
	scrollArea->setAlignment(Qt::AlignLeft|Qt::AlignTop);
	scrollAreaWidgetContents = new QWidget();
	scrollAreaWidgetContents->setObjectName(QString::fromUtf8("scrollAreaWidgetContents"));
//	scrollAreaWidgetContents->setGeometry(QRect(0, 0, 761, 80));
	scrollAreaWidgetContents->setLayout(formLay);

	scrollArea->setWidget(scrollAreaWidgetContents);

	layout->addWidget(scrollArea);
	layout->addWidget(botoes);
	setLayout(layout);

	connect(add, SIGNAL(pressed()), this, SLOT(adicionar()));
	connect(del, SIGNAL(pressed()), this, SLOT(remover()));

	connect(next, SIGNAL(pressed()), this, SLOT(nextForm()));
	connect(previous, SIGNAL(pressed()), this, SLOT(previousForm()));
}

void form_filling::novoFormulario(){

	formulario *f = new formulario(formList.size()+1);

	formList.insert(formList.size(), f);

	delete formLay;
	formLay = new QVBoxLayout;

	formLay->addWidget(f);

	scrollAreaWidgetContents->setLayout(formLay);
}

void form_filling::adicionar(){
	novoFormulario();
	qt++;

	if(qt>1) next->setEnabled(true);
	curNum->setValue(qt);
}

void form_filling::remover(){

	int i;
	bool onceAgain = true;

	again:
	while(onceAgain){
		onceAgain = false;

		for(i=0; i< formList.size(); i++){
				if(/*formList.at(i)->checkedForRemoval()*/false){
					delete formList.at(i);
					formList.removeAt(i);
					onceAgain = true;
					goto again;
				}
			}
	}

	for(i=0; i< formList.size(); i++){
		formList.at(i)->setNum(i+1);
	}
}

void form_filling::openForm(QString file)
{
    static int sequenceNumber = 1;
    int i;
    QList<QString> l;
    QList<query*> ret;

    isUntitled = true;
    curFile = file;//tr("formulario%1.tald").arg(sequenceNumber++);
    setWindowTitle(curFile + "[*]");

    //connect(document(), SIGNAL(contentsChanged()),
    //        this, SLOT(documentWasModified()));

    logica::abrir(curFile.toStdString().c_str(), ret);

	for(i=0; i<ret.size(); i++){
		l.append(ret.at(i)->getQuestion());
	}

	formulario *f = new formulario(formList.size()+1);
	f->setFields(l);

	//formList.insert(formList.size(), f);

	delete formLay;
	formLay = new QVBoxLayout;

	formLay->addWidget(f);

	scrollAreaWidgetContents->setLayout(formLay);

}

bool form_filling::loadFile(const QString &fileName)
{
    QFile file(fileName);
    if (!file.open(QFile::ReadOnly | QFile::Text)) {
        QMessageBox::warning(this, tr("Tallulah"),
                             tr("Cannot read file %1:\n%2.")
                             .arg(fileName)
                            .arg(file.errorString()));
        return false;
    }

    QTextStream in(&file);
    QApplication::setOverrideCursor(Qt::WaitCursor);
    //setPlainText(in.readAll());
    QApplication::restoreOverrideCursor();

    setCurrentFile(fileName);

    //connect(document(), SIGNAL(contentsChanged()),
    //        this, SLOT(documentWasModified()));

   return true;
}

QString form_filling::filename()
{
    if (isUntitled) {
        return newFilename();
    } else {
        return curFile;
    }
}

QString form_filling::newFilename()
{
    QString filename = QFileDialog::getSaveFileName(this, tr("Save As"),
                                                    curFile);
    /*if (fileName.isEmpty())
        return QString("");

    return saveFile(fileName);*/

    if (!filename.isEmpty()){
    	isUntitled = false;
    	curFile = filename;

    } else return QString("");

    return filename;
}

QList<formulario*>& form_filling::getFormList(){
	return formList;
}

bool form_filling::saveFile(const QString &fileName)
{
    QFile file(fileName);
    if (!file.open(QFile::WriteOnly | QFile::Text)) {
        QMessageBox::warning(this, tr("MDI"),
                             tr("Cannot write file %1:\n%2.")
                             .arg(fileName)
                             .arg(file.errorString()));
        return false;
    }

    QDataStream out(&file);
    QApplication::setOverrideCursor(Qt::WaitCursor);

//	for(int i = 0; i < tabs->rowCount(); i++) {
//		for(int j = 0; j < tabs->columnCount(); j++) {
			//(tabs->itemAt(i, j)).write(&out);
//		}
//	}

    QApplication::restoreOverrideCursor();
    setCurrentFile(fileName);
    return true;
}

QString form_filling::userFriendlyCurrentFile()
{
    return strippedName(curFile);
}

void form_filling::closeEvent(QCloseEvent *event)
{
    if (maybeSave()) {
        event->accept();
    } else {
        event->ignore();
    }
}

void form_filling::documentWasModified()
{
    setWindowModified(false/*document()->isModified()*/);
}

bool form_filling::maybeSave()
{
    if (/*document()->isModified()*/false) {
	QMessageBox::StandardButton ret;
        ret = QMessageBox::warning(this, tr("MDI"),
                     tr("'%1' has been modified.\n"
                        "Do you want to save your changes?")
                     .arg(userFriendlyCurrentFile()),
                     QMessageBox::Save | QMessageBox::Discard
		     | QMessageBox::Cancel);
        if (ret == QMessageBox::Save)
            return /*save()*/false;
        else if (ret == QMessageBox::Cancel)
            return false;
    }
    return true;
}

void form_filling::setCurrentFile(const QString &fileName)
{
    curFile = QFileInfo(fileName).canonicalFilePath();
    isUntitled = false;
    //document()->setModified(false);
    setWindowModified(false);
    setWindowTitle(userFriendlyCurrentFile() + "[*]");
}

QString form_filling::strippedName(const QString &fullFileName)
{
    return QFileInfo(fullFileName).fileName();
}

void form_filling::showForm(int qt){

}

void form_filling::nextForm(){
	qt++;
	if(qt == formList.size()){
		next->setEnabled(false);
	}

	showForm(qt);
	curNum->setValue(qt);

	previous->setEnabled(true);

}

void form_filling::previousForm(){

	qt--;
	if(qt <= 1){
		previous->setEnabled(false);
	}

	showForm(qt);
	curNum->setValue(qt);

	next->setEnabled(true);
}

